import 'package:flutter/material.dart';
import 'package:system_tray/system_tray.dart';
import 'package:window_manager/window_manager.dart';
import 'dart:io' show Platform;
import 'music_player_service.dart';

class SystemTrayService {
  static final SystemTray _systemTray = SystemTray();
  static bool _isInitialized = false;
  static MusicPlayerService? _musicPlayerService;

  static Future<void> initialize(MusicPlayerService musicPlayerService) async {
    if (_isInitialized || !Platform.isWindows) return;
    
    _musicPlayerService = musicPlayerService;
    await _initializeSystemTray();
  }

  static Future<void> _initializeSystemTray() async {
    try {
      String iconPath;
      if (Platform.isWindows) {
        iconPath = 'assets/images/tray_icon.ico';
      } else {
        iconPath = 'assets/images/tray_icon.png';
      }
      
      await _systemTray.initSystemTray(
        title: "洛页云音乐",
        iconPath: iconPath,
        toolTip: "洛页云音乐 - 音乐播放器",
      );

      // 设置托盘菜单
      await _setupTrayMenu();
      
      // 监听托盘点击事件
      _systemTray.registerSystemTrayEventHandler((eventName) {
        debugPrint("系统托盘事件: $eventName");
        if (eventName == kSystemTrayEventClick) {
          _toggleWindowVisibility();
        } else if (eventName == kSystemTrayEventRightClick) {
          _systemTray.popUpContextMenu();
        }
      });

      _isInitialized = true;
      debugPrint("系统托盘初始化成功");
    } catch (e) {
      debugPrint("系统托盘初始化失败: $e");
      // 如果托盘初始化失败，我们仍然可以使用窗口管理功能
    }
  }

  static Future<void> _setupTrayMenu() async {
    final Menu menu = Menu();
    
    // 播放/暂停菜单项
    await menu.buildFrom([
      MenuItemLabel(
        label: '显示/隐藏窗口',
        onClicked: (menuItem) => _toggleWindowVisibility(),
      ),
      MenuSeparator(),
      MenuItemLabel(
        label: '播放/暂停',
        onClicked: (menuItem) => _togglePlayPause(),
      ),
      MenuItemLabel(
        label: '上一首',
        onClicked: (menuItem) => _previousTrack(),
      ),
      MenuItemLabel(
        label: '下一首',
        onClicked: (menuItem) => _nextTrack(),
      ),
      MenuSeparator(),
      MenuItemLabel(
        label: '退出',
        onClicked: (menuItem) => _exitApp(),
      ),
    ]);

    await _systemTray.setContextMenu(menu);
  }

  static Future<void> _toggleWindowVisibility() async {
    try {
      bool isVisible = await windowManager.isVisible();
      if (isVisible) {
        await windowManager.hide();
      } else {
        await windowManager.show();
        await windowManager.focus();
      }
    } catch (e) {
      debugPrint("切换窗口可见性失败: $e");
    }
  }

  static void _togglePlayPause() {
    if (_musicPlayerService != null) {
      if (_musicPlayerService!.isPlaying) {
        _musicPlayerService!.pause();
      } else {
        _musicPlayerService!.resume();
      }
    }
  }

  static void _previousTrack() {
    _musicPlayerService?.previous();
  }

  static void _nextTrack() {
    _musicPlayerService?.next();
  }

  static Future<void> _exitApp() async {
    await _systemTray.destroy();
    await windowManager.destroy();
  }

  static Future<void> updateTrayTooltip(String tooltip) async {
    if (_isInitialized) {
      await _systemTray.setToolTip(tooltip);
    }
  }

  static Future<void> dispose() async {
    if (_isInitialized) {
      await _systemTray.destroy();
      _isInitialized = false;
    }
  }
}